//
//  XYCRouteHandler.m
//  WLRRoute_Example
//
//  Created by xyc on 2018/2/7.
//  Copyright © 2018年 Neo. All rights reserved.
//

#import "XYCRouteHandler.h"
#import "NSError+XYCRouteError.h"
#import "UIViewController+XYCRoute.h"

@implementation XYCRouteHandler

//这个需要被具体的handler重写。
-(UIViewController *)targetViewControllerWithRequest:(XYCRouteRequest *)request{
    
    return [[NSClassFromString(@"HBTestViewController") alloc]init];
}

-(UIViewController *)sourceViewControllerForTransitionWithRequest:(XYCRouteRequest *)request{
    
    return [UIApplication sharedApplication].windows[0].rootViewController;
}

-(BOOL)handleRequest:(XYCRouteRequest *)request error:(NSError *__autoreleasing *)error{
   
    UIViewController * sourceViewController = [self sourceViewControllerForTransitionWithRequest:request];
    UIViewController * targetViewController = [self targetViewControllerWithRequest:request];
    if ((![sourceViewController isKindOfClass:[UIViewController class]])||(![targetViewController isKindOfClass:[UIViewController class]])) {
        
        //两个都必须是vc，否则返回错误
        *error = [NSError XYCRouteTransitionError];
        return NO;
    }
    if (targetViewController != nil) {
        
        //将请求request复制给目标vc，这样目标vc就可以通过request获取传递过来的参数了
        targetViewController.routeRequest = request;
    }
    return [self transitionWithWithRequest:request sourceViewController:sourceViewController targetViewController:targetViewController error:error];
}

-(BOOL)transitionWithWithRequest:(XYCRouteRequest *)request sourceViewController:(UIViewController *)sourceViewController targetViewController:(UIViewController *)targetViewController error:(NSError *__autoreleasing *)error{
    
    if (![sourceViewController isKindOfClass:[UINavigationController class]]) {
        
        [sourceViewController presentViewController:targetViewController animated:YES completion:nil];
    } else if ([sourceViewController isKindOfClass:[UINavigationController class]]){
        
        UINavigationController * nav = (UINavigationController *)sourceViewController;
        [nav pushViewController:targetViewController animated:YES];
    }
    return YES;
}

@end
